//
//  AppDelegate.swift
//  Weibo
//
//  Created by apple on 15/6/24.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import AFNetworking

var sharedUserAccount = UserAccount.loadAccount()
let LLSwitchRootVCNotification = "LLSwitchRootVCNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        

        setupNetWork()
        setapprance()
       
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defaultViewController()
        window?.makeKeyAndVisible()
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: LLSwitchRootVCNotification, object: nil)
        return true
    }
    ///  注销通知
    deinit {
    
    NSNotificationCenter.defaultCenter().removeObserver(self, name: LLSwitchRootVCNotification, object: nil)
    
    }
    ///  切换控制器
    func switchViewController(n: NSNotification) {
        // 判断 object 是否为 true，如果是，显示 MainViewController
        let isMainVC = n.object as! Bool
        
        window?.rootViewController = isMainVC ? MainViewController() : WelcomeViewController()
    }

    
    
    ///  判断加载的默认控制器
    private func defaultViewController() -> UIViewController {
        
        // 1. 判断用户是否登录
        if sharedUserAccount != nil {
            
            // 2. 如果登录，判断是否有新版本
            return isNewUpdate() ? NewFeatureViewController() : WelcomeViewController()
        }
        
        return MainViewController()
    }
    
    
///  检查新版本
    private func isNewUpdate() ->Bool {
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(currentVersion)!
        print(version)
        
        let versionKey = "versionKey"
        let sandBoxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        print(sandBoxVersion)
        

        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: versionKey)
     
        
        return version > sandBoxVersion
    
    
    }
    
    
    
    //设置网络
    func setupNetWork (){
    
        // 设置网路指示器
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        // 设置网络缓存
        let urlCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
        NSURLCache.setSharedURLCache(urlCache)
    
    }
    //设置外观
    func setapprance(){
    UITabBar.appearance().tintColor = UIColor.orangeColor()
    UINavigationBar.appearance().tintColor = UIColor.orangeColor()
    }
   
}

